﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using bzxxxt.admin.service;
using bzxxxt.dal;
using bzxxxt.model;

namespace bzxxxt.bll
{
    public class EcoBuralBLL : BaseBLL
    {
        admin.entity.UserEntity user = admin.service.UserService.GetUser(HttpContext.Current);   //获取cookie里的用户对象
        public string GetListByPage(int pageSize, int pageIndex, string sort, string where = "1=1")
        {
            int totalCount = 0;

            if (user.roleNames.Contains("镇级管理员"))
            {
                var u = DB.tbUser.FirstOrDefault(m => m.id == user.id);
                var codes = u.tbDepartment.Select(m => m.code).ToList();
                string code = "";
                codes.ForEach(m => { code += m + ","; });
                code = code.Trim(',');
                where = string.Format("(left(paradisecode,2) IN ({0})) and ", code) + where;
            }
            else if (user.roleNames.Contains("骨灰堂管理员"))
            {
                var u = DB.tbUser.FirstOrDefault(m => m.id == user.id);
                var codes = u.tbUserParadise.Select(m => m.tbParadise.code).ToList();
                string code = "";
                codes.ForEach(m => { code += m + ","; });
                code = code.Trim(',');
                where = string.Format("(paradisecode IN ({0})) and ", code) + where;
            }

            SqlParameter paramTableName = new SqlParameter("@tableName", "tbEcoBural");
            SqlParameter paramColumns = new SqlParameter("@columns", "*");
            SqlParameter paramOrder = new SqlParameter("@order", sort);
            SqlParameter paramPageSize = new SqlParameter("@pageSize", pageSize);
            SqlParameter paramPageIndex = new SqlParameter("@pageIndex", pageIndex);
            SqlParameter paramWhere = new SqlParameter("@where", where);
            SqlParameter paramTotalCount = new SqlParameter("@totalCount", totalCount);
            paramTotalCount.Direction = ParameterDirection.Output;
            var p = DB.tbEcoBural.SqlQuery("exec sp_Pager @tableName,@columns,@order,@pageSize,@pageIndex,@where,@totalCount output",
                new SqlParameter[] { paramTableName, paramColumns, paramOrder, paramPageSize, paramPageIndex, paramWhere, paramTotalCount }).ToList();
            totalCount = Convert.ToInt32(paramTotalCount.Value);

            var list = from d in p
                       select new EcoBuralModel
                       {
                           id = d.id,
                           paradisecode = d.paradisecode,
                           paradiseid = d.paradiseid,
                           paradiseName = d.tbParadise.name,
                           storetype = d.storetype,

                           deadId = d.deadid,
                           deadName = d.tbDead.name,
                           deadAreaName = d.tbDead.tbArea!=null?d.tbDead.tbArea.name : "",
                           deadAreaCode = d.tbDead.tbArea!=null?d.tbDead.tbArea.code:"",
                           deadCardno = d.tbDead.cardno,
                           deadGender = d.tbDead.gender,
                           deadHomeAddr  = d.tbDead.homeAddress,
                           relation = d.tbDead.relationid,
                           deadNation = d.tbDead.nationid,
                           deadFireTime = d.tbDead.actFiretime,

                           relativeId = d.tbDead.relativeid,
                           relativeName = d.tbDead.tbRelative==null ? "": d.tbDead.tbRelative.name,
                           relativeTel =  d.tbDead.tbRelative==null ? "" : d.tbDead.tbRelative.tel,
                           reltiveCardNo = d.tbDead.tbRelative == null ? "" : d.tbDead.tbRelative.cardno,
                           reltiveAreaCode = (d.tbDead.tbRelative == null  || d.tbDead.tbRelative.tbArea == null) ?"": d.tbDead.tbRelative.tbArea.code,
                           reltiveAreaName = (d.tbDead.tbRelative == null || d.tbDead.tbRelative.tbArea == null) ? "" :d.tbDead.tbRelative.tbArea.name ,
                           
                           addtime  = d.addtime
                       };
            
            string json = JsonUtil.ToJson(new { total = totalCount, rows = list.ToList() });
            return json;
        }

        public string Add(EcoBuralModel em) {
            tbDead dead = new tbDead();
            dead.name = em.deadName;
            dead.areacode = em.deadAreaCode;
            dead.gender = em.deadGender;
            dead.cardno = em.deadCardno;
            dead.cardtype = "身份证";
            dead.homeAddress = em.deadHomeAddr;
            dead.addtime = DateTime.Now;
            dead.storetype = "生态葬";
            dead.relationid = em.relation;
            dead.nationid = em.deadNation;
            dead.actFiretime = em.deadFireTime;

            tbRelative relative = new tbRelative();
            relative.name = em.relativeName;
            relative.areacode = em.reltiveAreaCode;
            relative.tel = em.relativeTel;
            relative.addtime = DateTime.Now;
            relative.cardno = em.reltiveCardNo;
            dead.tbRelative = relative;

            tbEcoBural eb = new tbEcoBural();
            var paradise = DB.tbParadise.FirstOrDefault(m => m.code == em.paradisecode);
            eb.paradisecode = paradise.code;
            eb.paradiseid = paradise.id;
            eb.areacode = em.areacode;

            eb.storetype = em.storetype;
            eb.tbDead = dead;
            eb.addtime = DateTime.Now;

            DB.tbRelative.Add(relative);
            DB.tbDead.Add(dead);
            DB.tbEcoBural.Add(eb);

            DB.SaveChanges();

           

            string json = JsonUtil.ToJson(new {success = true,msg="添加成功！" });
            return json;
        }

        public string Edit(EcoBuralModel em)
        {
            var eb = DB.tbEcoBural.FirstOrDefault(m => m.id == em.id);
            if(eb.paradisecode!=em.paradisecode){
                var paradise = DB.tbParadise.FirstOrDefault(m => m.code == em.paradisecode);
                eb.paradisecode = em.paradisecode;
                eb.paradiseid = em.paradiseid;
                eb.tbParadise = paradise;
            }
            eb.storetype = em.storetype;
            eb.areacode = em.areacode;

            tbDead dead = eb.tbDead;
            dead.name = em.deadName;
            dead.areacode = em.deadAreaCode;
            dead.gender = em.deadGender;
            dead.cardno = em.deadCardno;
            dead.cardtype = "身份证";
            dead.updatetime = DateTime.Now;
            dead.homeAddress = em.deadHomeAddr;
            dead.storetype = "生态葬";
            dead.relationid = em.relation;
            dead.nationid = em.deadNation;
            dead.actFiretime = em.deadFireTime;

            tbRelative relative = eb.tbDead.tbRelative;
            if (relative == null) {
                relative = DB.tbRelative.FirstOrDefault(m => m.name == em.relativeName && m.areacode == em.reltiveAreaCode && m.tel == em.relativeTel);
                if (relative == null)
                {
                    relative = new tbRelative();
                }
                eb.tbDead.tbRelative = relative;
            }
            relative.name = em.relativeName;
            relative.areacode = em.reltiveAreaCode;
            relative.tel = em.relativeTel;
            relative.updatetime = DateTime.Now;
            relative.cardno = em.reltiveCardNo;
            
            DB.SaveChanges();

            string json = JsonUtil.ToJson(new { success = true, msg = "修改成功！" });
            return json;
        }

        public string Delete(int id)
        {
            var eco = DB.tbEcoBural.FirstOrDefault(m => m.id == id);
            DB.tbEcoBural.Remove(eco);
            DB.SaveChanges();
            string json = JsonUtil.ToJson(new { success = true, msg = "删除成功！" });
            return json;
        }
    }
}